<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/7/31 17:47
 */

namespace App\Project\Reserve\Behaviours;

use App\Models\Reservation\Reservation;
use App\User;
use Illuminate\Database\Eloquent\Builder;

class Look
{
    protected $user;

    /**
     * @var \Illuminate\Database\Eloquent\Builder|Reservation
     */
    protected $reservation;

    protected $where = [];

    protected $wherePatient;

    /**
     * Look constructor.
     * @param \App\User $user
     * @param null      $reservation
     */
    public function __construct(User $user, $reservation = null)
    {
        $this->user = $user;

        $this->reservation = $reservation ?: Reservation::with('patient');
    }

    /**
     * @param       $id
     * @param array $columns
     * @param bool  $withTrashed
     * @return \Illuminate\Database\Eloquent\Collection|Reservation|null
     */
    public function find($id, $columns = ['*'], $withTrashed = false)
    {
        $this->withTrashed($withTrashed);

        return $this->reservation->find($id, $columns);
    }

    /**
     * 设置查找某个医生的预约条件, 根据医生权限设置查询条件
     * @param \App\User $user
     * @return Look
     */
    public function forUser($user = null)
    {
        if (empty($user)) {
            if (!$this->user->isA('nurse')) {
                $this->reservation->where(['doctor_id' => $this->user->id]);
            }
        } else {
            if ($this->user->isA('nurse')) {
                $this->reservation->where(['doctor_id' => $user]);
            } else {
                $this->reservation->where(['doctor_id' => $this->user->id]);
            }
        }

        return $this;
    }

    /**
     * @param array $wherePatient
     * @return Look
     */
    public function wherePatient(array $wherePatient)
    {
        $this->reservation->wherePatient($wherePatient);

        return $this;
    }

    /**
     * @param array $whereReserve
     * @return Look
     */
    public function whereReserve(array $whereReserve)
    {
        if ($whereReserve) {
            $this->reservation->where($whereReserve);
        }

        return $this;
    }

    /**
     * @param bool $withTrashed
     * @return $this
     */
    protected function withTrashed($withTrashed = false)
    {
        if ($withTrashed) {
            $this->reservation = $this->reservation->withTrashed();
        }

        return $this;
    }

    /**
     * 调用不存在的方法时，去调用模型的方法, 并返回模型
     * @param $method
     * @param $arguments
     * @return \Illuminate\Database\Eloquent\Collection|Reservation|null
     */
    public function __call($method, $arguments)
    {
        return $this->reservation->$method(...$arguments);
    }
}